package com.develop.data.loan.jpa.attribute.converter;


import com.develop.data.loan.model.LoanInstallment;
import com.develop.data.loan.repository.LoanInstallmentRepository;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Converter
public class LoanInstallmentListAttributeConverter implements AttributeConverter<List<LoanInstallment>, String> {

    @Autowired
    LoanInstallmentRepository loanInstallmentRepository;

    @Override
    public String convertToDatabaseColumn(List<LoanInstallment> loanInstallments) {
        return loanInstallments.stream().map(LoanInstallment::getId).collect(Collectors.joining(","));
    }

    @Override
    public List<LoanInstallment> convertToEntityAttribute(String ids) {
        if (ids == null) return null;
        return loanInstallmentRepository.findAllById(Arrays.asList(ids.split(",")));
    }
}

